import { AuthProvider, useAuth } from '@/contexts/AuthContext'
import { supabase } from '@/lib/supabase'
import { getUserData } from '@/services/userService'
import { Stack, useRouter } from 'expo-router'
import { useEffect } from 'react'
import { StyleSheet } from 'react-native'

const _layout = () => {
  return (
    <AuthProvider>
      <MainLayout />
    </AuthProvider>
  )
}

const MainLayout = () => {
  const router = useRouter()
  const { setAuth, setUserData } = useAuth()

  useEffect(() => {
    supabase.auth.onAuthStateChange((event, session) => {
      console.log('session user', session?.user?.id)

      if (session) {
        setAuth(session?.user)
        updateUserData(session?.user, session?.user.email)
        router.replace('/home')
      } else {
        setAuth(null)
        router.replace('/welcome')
      }
    })
  }, [])

  const updateUserData = async (user, email) => {
    let res = await getUserData(user?.id)
    setUserData({ ...res.data, email })
  }

  return (
    <Stack
      screenOptions={{
        headerShown: false,
      }}
    />
  )
}

export default _layout

const styles = StyleSheet.create({})
